import { Body, Inject, Post, Provide, Get } from '@midwayjs/decorator';
import { CoolController, BaseController, CoolCommException } from '@cool-midway/core';
import { Context } from 'egg';
import { ImMessageEntity } from '../../entity/message';
import { ImMessageService } from '../../service/message';
import { ImSocketEvent } from '../../socket/event';
import { ImUserService } from '../../service/user';


/**
 * 描述
 */
@Provide()
@CoolController({
  api: ['page'],
  entity: ImMessageEntity,
  service: ImMessageService,
})
export class imMessageController extends BaseController {
  @Inject()
  imMessageService: ImMessageService;

  @Inject()
  imSocketEvent: ImSocketEvent;

  @Inject()
  imUserService: ImUserService;

  @Inject()
  ctx: Context;

  /**
   * 已读
   * @param messageIds
   * @param sessionId
   * @returns
   */
  @Post('/read')
  async read(@Body() ids: number[], @Body() session: number) {
    this.imMessageService.read(ids, session, 1);
    return this.ok();
  }
  /**
   * 全部已读
   * @param messageIds
   * @param sessionId
   * @returns
   */
  @Post('/readAll')
  async readAll(@Body() sessionId: number) {
    this.imMessageService.readAll(sessionId, 1, this.ctx.user.id);
    return this.ok();
  }

  @Get('/count')
  async count() {
    return this.ok(await this.imMessageService.unCount(this.ctx.user.id));
  }


  @Post('/send')
  async sendMessage(@Body() id: string, @Body() msg: any) {
    console.log('isOnline====111111111=>', msg);
    const user = await this.imUserService.findOne({ userId: id, type: 1 })
    if (!user) {
      throw new CoolCommException('对不起，当前用户不在线！');
    }
    if (user && user.socketId) {
      const isOnline = await this.imSocketEvent.online(user.socketId)
      console.log('isOnline=====>', isOnline);
      if (isOnline) {
        return this.ok(await this.imSocketEvent.sendMessage(user.socketId, msg));
      } else {
        throw new CoolCommException('对不起，当前用户不在线！');
      }
    }
  }
}
